package com.nulldev.util.web.HttpServer3.extensions.protected_content;

import java.util.concurrent.TimeUnit;

import com.nulldev.util.VariableAPI.RandomUtil;
import com.nulldev.util.VariableAPI.StringsUtil;
import com.nulldev.util.data.Variables;
import com.nulldev.util.data.Arrays.caches.LRUCache;
import com.nulldev.util.data.Base62.Base62;
import com.nulldev.util.web.HttpServer3.Page;

public class ProtectedContentTokens {

	private static final LRUCache<String, ProtectedContentEntry> content_tokens = new LRUCache<String, ProtectedContentEntry>(512, 1, TimeUnit.MINUTES);

	private static final String __make_token() {
		final byte[] data = RandomUtil.bytes(64);
		return Base62.createInstanceWithCompat().encodeToString(data);
	}

	public static String issueToken(final Page page, final long amount, final TimeUnit unit) {
		Variables.requireNonNull(page, "page");
		Variables.requireNonNull(unit, "unit");
		final long ms = unit.toMillis(amount);
		final String cs = __make_token();
		final long exp = System.currentTimeMillis() + ms;
		content_tokens.put(cs, new ProtectedContentEntry(exp, page.pc_get_uuid()));
		return cs;
	}

	public static boolean validateToken(final Page page, final String token) {
		/* Reject invalid pages. */
		if (page == null)
			return false;
		/* Reject invalid tokens */
		if (StringsUtil.isBlank(token))
			return false;
		final ProtectedContentEntry entry = content_tokens.get(token);
		/* Check for token presence. */
		if (entry == null)
			return false;
		/* If the UUIDs don't match, the token is not being used correctly. */
		if (!page.pc_get_uuid().equals(entry.page_uuid()))
			return false;
		/* Finally check for validity. */
		return entry.expiry() < System.currentTimeMillis();
	}
}
